package com.flower.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flower.salary.common.utils.*;
import com.flower.salary.domain.bo.AddUserBO;
import com.flower.salary.domain.bo.UserBanBO;
import com.flower.salary.domain.entity.SysDept;
import com.flower.salary.domain.entity.SysUser;
import com.flower.salary.domain.entity.SysUserSalary;
import com.flower.salary.domain.vo.ListUserVO;
import com.flower.salary.domain.vo.SysUserVO;
import com.flower.salary.domain.vo.UserInfoVO;
import com.flower.salary.mapper.SysDeptMapper;
import com.flower.salary.mapper.SysUserMapper;
import com.flower.salary.mapper.SysUserSalaryMapper;
import com.flower.salary.service.SysLogService;
import com.flower.salary.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author lavender
 * @version 1.0
 * @date 2023-12-20 21:32
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysLogService logService;


    @Autowired
    private SysUserSalaryMapper sysUserSalaryMapper;


    @Override
    public String logon(String username, String password) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser==null){
            throw  new SalaryException("账号不存在");
        }
        // 获取盐值
        String salt = sysUser.getSalt();

        String newPassword = password + salt;

        String md5Str = MD5Utils.getMD5Str(newPassword);

        if("1".equals(sysUser.getStatus())){
            throw  new SalaryException("账号被冻结");
        }

        if(sysUser.getPassword().equals(md5Str)){
            logService.insert("登陆成功",sysUser.getUserName(), LogLevel.INFO);
            // 把token返回回去
            String token = JwtUtil.createToken(sysUser.getUserId().intValue());
            // todo 后续登录扩展
            LocalUser.setLocalUser(sysUser);
            return token;
        }else {

            throw  new SalaryException("账号密码错误");
        }

    }

    @Override
    public SysUserVO info(String token) {
        int userId = JwtUtil.getUserId(token);
        SysUser sysUser = userInfo(userId);
        SysUserVO vo = new SysUserVO();
        vo.setAvatar(sysUser.getAvatar());
        vo.setUsername(sysUser.getLoginName());
        logService.insert("查看信息",sysUser.getUserName(), LogLevel.INFO);
        return vo;
    }

    @Override
    public UserInfoVO userInfo(String token) {
        // 获取用户id
        int userId = JwtUtil.getUserId(token);
        // 获取用户信息
        SysUser sysUser = userInfo(userId);
        // 查询部门信息
        QueryWrapper q = new QueryWrapper();
        q.eq("dept_id",sysUser.getDeptId());
        SysDept sysDept = sysDeptMapper.selectOne(q);
        if(sysDept==null){
            throw  new SalaryException("查询部门信息失败");
        }
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(sysUser,vo);
        vo.setDeptName(sysDept.getDeptName());
        return vo;
    }

    @Override
    public List<ListUserVO> selectList() {

        QueryWrapper q = new QueryWrapper();

        List<SysUser> lists = sysUserMapper.selectList(q);
        List<ListUserVO> user= new ArrayList<>();

        for(SysUser u:lists){
            ListUserVO vo = new ListUserVO();
            BeanUtils.copyProperties(u,vo);

          user.add(vo);
        }
        logService.insert("查询所有用户信息", LogLevel.WARNING);
        return user;
    }

    @Override
    public int ban(UserBanBO bo) {
        QueryWrapper q = new QueryWrapper();
        q.eq("login_name",bo.getName());
        SysUser sysUser = sysUserMapper.selectOne(q);
        sysUser.setStatus(bo.getStatus());
        int i = sysUserMapper.updateById(sysUser);

        if(i==0){
            throw  new SalaryException("冻结用户失败");
        }
        logService.insert("冻结用户" + sysUser.getUserName(), LogLevel.DANGETOUS);
        return 1;
    }

    @Override
    public int editPassword(String token, String password) {
        // 获取用户id
        int userId = JwtUtil.getUserId(token);
        // 获取用户信息
        SysUser sysUser = userInfo(userId);
        // 加盐设置新的密码
        String newPassword = MD5Utils.getMD5Str( password + sysUser.getSalt());
        sysUser.setPassword(newPassword);
        int i = sysUserMapper.updateById(sysUser);
        if (i==0) {
            throw  new SalaryException("修改密码失败");
        }
        logService.insert("修改密码" , LogLevel.DANGETOUS);
        return 1;
    }

    @Override
    public int updateUserInfo(UserInfoVO vo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo,user);
        int i = sysUserMapper.updateById(user);
        if(i==0){
            throw  new SalaryException("修改个人消息失败");
        }
        logService.insert("修改个人消息" , LogLevel.INFO);
        return 0;
    }

    @Override
    public int addUser(AddUserBO bo) {
        SysUser user = new SysUser();
        checkUserNameUnique(bo.getLoginName());
        user.setUserName(bo.getUserName());
        user.setLoginName(bo.getLoginName());
        /**
         * 公司内部系统 密码默认123456
         */
        Random random = new Random();
        int salt = random.nextInt(900000) + 100000;
        user.setSalt(salt + "");
        String password = MD5Utils.getMD5Str( "123456" +  salt);
        user.setPassword(password);
        // todo 后期修改
        user.setDeptId(bo.getDeptId());
        user.setUserType("11");
        user.setStatus("0");
        user.setAvatar("https://img1.baidu.com/it/u=3659556470,999557894&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703264400&t=cbd27c189d7652982c95c4a0095bd6ab");
        user.setCreateBy("admin");
        user.setSex("0");
        user.setCreateTime(LocalDateTime.now());
        user.setEmail("12306@qq.com");
        user.setPhonenumber("18888888888");
        user.setLoginIp("127.0.0.1");
        user.setDelFlag("0");
        user.setLoginDate(LocalDateTime.now());
        int insert = sysUserMapper.insert(user);
        if(insert==0){
            throw  new SalaryException("新增用户失败");
        }
        Long userId = user.getUserId();
        // 工资表
        SysUserSalary sysUserSalary = new SysUserSalary();
        sysUserSalary.setId(userId.intValue());
        sysUserSalary.setName(bo.getUserName());
        sysUserSalary.setBasicSalary(bo.getBasicSalary());


        sysUserSalary.setPosition("正式员工");
        sysUserSalary.setBonus(bo.getBonus());
        sysUserSalary.setTaxDeduction(bo.getTaxDeduction());
        sysUserSalary.setNetSalary(bo.getNetSalary());
        sysUserSalary.setState(0);
        int insert1 = sysUserSalaryMapper.insert(sysUserSalary);

        logService.insert("创建用户" , LogLevel.INFO);
        return 0;
    }

    @Override
    public int checkUserNameUnique(String username) {
        QueryWrapper q = new QueryWrapper();
        q.eq("login_name",username);
        SysUser sysUser = sysUserMapper.selectOne(q);
        if(sysUser!=null){
            throw new SalaryException("该用户已存在");
        }

        return 0;
    }

    private SysUser userInfo(int userId){
        return sysUserMapper.selectById(userId);
    };

}
